package org.example.forum.exception;

import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationExceptionHandler (ApplicationException e) {
        //打印异常信息
        e.printStackTrace();
        //打印日志
        log.error(e.getMessage());
        if(null!=e.getErrorResult()) {
            return e.getErrorResult();
        }
        if(null == e.getMessage()|| "".equals(e.getMessage())) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        //返回具体的错误信息
        return AppResult.failed(e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler (Exception e) {
        //打印异常信息
        e.printStackTrace();
        //打印日志
        log.error(e.getMessage());

        if(null == e.getMessage()|| "".equals(e.getMessage())) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        //返回具体的错误信息
        return AppResult.failed(e.getMessage());
    }

}
